#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  add_doc_for_gen.py
#       Author @  Huoty
#  Create date @  2016-03-29 18:56:37
#  Description @  
# *************************************************************

import csv
import re
import sys

def add_doc(genfile, csvfile):
    csv_fo = open(csvfile, "rb")
    csv_reader = csv.DictReader(csv_fo)
    comments = {}
    try:
        for row in csv_reader:
            if len(row["Comment"]) != 0:
                comments[row["Field"].strip()] = row["Comment"].strip()
    except KeyError:
        print "Notice: File format of CSV was invalid!"
        return False

    csv_fo.close()

    count_re = 0
    new_content = ""
    with open (genfile, "r") as gen_fo:
        for each_line in gen_fo:
            for field, comment in comments.iteritems():
                regex = "\s" + field + " = Column"
                if re.search(regex, each_line):
                    new_line = [each_line.rstrip()[0:-1], ', doc="', comment, '")\n']
                    each_line = "".join(new_line)
                    count_re += 1
                
            new_content += each_line

    if count_re == 0:
        print "Notice: No content to be replaced!"
        return False
    else:
        print new_content
        return True

def usage():
    print u"Usage:\tdd_doc_for_gen.py <srcfile> <csvfile>"

# Script starts from here

if __name__ == "__main__":
    if len(sys.argv) != 3:
        usage()
    else:
        if not add_doc(sys.argv[1], sys.argv[2]):
            usage()

